import axios, {
    AxiosRequestConfig,
    AxiosError,
    AxiosResponse,
    InternalAxiosRequestConfig,
  } from "axios";
  import { storeToRefs } from "pinia";
  import router from "@/router";
  
  export interface ApiRequest {
    [index: string]: any;
  }
  
  export interface ApiResponse<T> {
    code: number;
    msg: string;
    data?: T;
  }
  export type TypeResponse<T> = Promise<ApiResponse<T>>;
  
  const Api = axios.create({
    // baseURL: "http://wuliu.com/index.php",
    timeout: 50000,
  });
  // Api.interceptors.request.use(
  //   (config: any) => {
  //     config = interceptorsHeader(config, token);
  //     return config;
  //   },
  //   (err) => {
  //     return Promise.reject(err);
  //   }
  // );
  
  // Api.interceptors.response.use((res: any) => {
  //   if (res.data.code === 400 || res.data.msg === "无效token") {
  //     const store = useUserStore();
  //     store.logout();
  //     ElMessage({
  //       type: "error",
  //       message: "用户登录状态失效,请重新登录",
  //       grouping: true,
  //     });
  //     router.push({
  //       path: "/login",
  //     });
  //   }
  //   return res;
  // });
  
  function request<T>(config: AxiosRequestConfig): TypeResponse<T> {
    return new Promise((resolve, reject) => {
      Api.request(config)
        .then((res: AxiosResponse) => {
          resolve(res.data as ApiResponse<T>);
        })
        .catch((err: AxiosError) => {
          // const error = ReturnMistake<T>(err)
          reject(err);
        });
    });
  }
  export const GET = <T>(
    url: string,
    params: ApiRequest = {}
  ): TypeResponse<T> => {
    return request({
      url: url,
      method: "get",
      params: params,
    });
  };
  export const Post = <T>(
    url: string,
    data: ApiRequest = {},
    params: ApiRequest = {}
  ): TypeResponse<T> => {
    return request({
      url: url,
      method: "post",
      data: data,
      params: params,
    });
  };
  
  export const Put = <T>(
    url: string,
    data: ApiRequest = {},
    params: ApiRequest = {}
  ): TypeResponse<T> => {
    return request({
      url: url,
      method: "put",
      data: data,
      params: params,
    });
  };
  
  export const Dele = <T>(
    url: string,
    params: ApiRequest = {}
  ): TypeResponse<T> => {
    return request({
      url: url,
      method: "delete",
      params: params,
    });
  };
  
  const interceptorsHeader = (
    config: AxiosRequestConfig,
    token: string
  ): AxiosRequestConfig => {
      config.headers = {
        "Content-Type": "applicatin/json",
      };
    return config;
  };
  